﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Epam.PeopleModel;

namespace PeopleListTask.CustomDataBinders
{
    public class NewsModelBinder:DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var created = DateTime.Now;
            var id = Guid.NewGuid();
            if(controllerContext.HttpContext.Request["Created"]!=null)
            {
                if (!DateTime.TryParse(controllerContext.HttpContext.Request["Created"], out created))
                    bindingContext.ModelState.AddModelError("Created", "Invalid date");
            }
            if (controllerContext.HttpContext.Request["Id"] != null)
            {
                if (!Guid.TryParse(controllerContext.HttpContext.Request["Id"], out id))
                    bindingContext.ModelState.AddModelError("Id", "Invalid id");
            }
            var entity= new NewsEntity(id, controllerContext.HttpContext.Request["Text"],
                controllerContext.HttpContext.Request["Title"],
                created);
            ValidateText(entity,bindingContext);
            ValidateTitel(entity,bindingContext);
            return entity;
        }

        protected void ValidateText(NewsEntity entity, ModelBindingContext bindingContext)
        {
            try
            {
                Validator.ValidateProperty(entity.Text,
                                           new ValidationContext(entity, null, null) { MemberName = "Text" });
            }
            catch (ValidationException e)
            {
                bindingContext.ModelState.AddModelError("Text", e);
            }
        }

        protected void ValidateTitel(NewsEntity entity, ModelBindingContext bindingContext)
        {
            try
            {
                Validator.ValidateProperty(entity.Title,
                                           new ValidationContext(entity, null, null) { MemberName = "Title" });
            }
            catch (ValidationException e)
            {
                bindingContext.ModelState.AddModelError("Title", e);
            }
        }
    }
}